package org.luxor.commons.log.component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;


public class HttpResponseWrapper extends HttpServletResponseWrapper {

    private ByteArrayOutputStream byteArrayOutputStream;
    private HttpServletResponse response;

    public HttpResponseWrapper(HttpServletResponse response) {
        super(response);
        this.byteArrayOutputStream = new ByteArrayOutputStream();
        this.response = response;
    }

    @Override
    public ServletOutputStream getOutputStream() {
        return new ExtendOutputStream(this.byteArrayOutputStream, this.response, true);
    }

    @Override
    public PrintWriter getWriter() {
        return new PrintWriter(byteArrayOutputStream, false);
    }

    @Override
    public void reset() {
        this.byteArrayOutputStream.reset();
    }

    @Override
    public void resetBuffer() {
        this.reset();
    }

    @Override
    public void flushBuffer() throws IOException {
        if (!this.response.isCommitted()) {
            ServletOutputStream outputStream = this.response.getOutputStream();
            byte[] body = this.byteArrayOutputStream.toByteArray();
            outputStream.write(body);
            outputStream.flush();
        }
    }

    public byte[] getContext() {
        return this.byteArrayOutputStream.toByteArray();
    }

    public void setContext(byte[] bytes, boolean autoFlush) throws IOException {
        this.reset();
        this.getOutputStream().write(bytes);
        if (autoFlush) {
            this.flushBuffer();
        }
    }

    @Override
    public String toString() {
        return new String(this.byteArrayOutputStream.toByteArray());
    }

}